<template>
    <div class="ability-page">
        <!-- 顶部工具条 -->
        <div class="toolbar">
            <div class="toolbar-left">
                <a-space>
                    <a-button type="primary" @click="onAdd">新增</a-button>
                    <!-- 批量操作 -->
                    <a-button :disabled="!selectedRowKeys.length" danger @click="onBatchDelete">批量删除</a-button>
                    <a-button :disabled="!selectedRowKeys.length" @click="onBatchEnable">批量启用</a-button>
                    <a-button :disabled="!selectedRowKeys.length" @click="onBatchDisable">批量停用</a-button>
                    <!-- 全部操作 -->
                    <a-divider type="vertical" />
                    <a-button :disabled="!pageData.length" ghost @click="onAllEnable">全部启用</a-button>
                    <a-button :disabled="!pageData.length" ghost @click="onAllDisable">全部停用</a-button>
                </a-space>
            </div>

            <div class="toolbar-right">
                <a-input-search v-model:value="keyword" placeholder="输入搜索" allow-clear enter-button="搜索"
                    style="width: 260px" @search="onSearch" />
            </div>
        </div>

        <!-- 表格滚动区 -->
        <div class="table-scroll">
            <div class="table-wrap">
                <a-table row-key="id" :data-source="pageData" :columns="columns" :loading="loading"
                    :row-selection="rowSelectionCfg" :pagination="false" bordered size="middle" :customRow="customRow"
                    :rowClassName="() => 'clickable-row'">
                    <template #bodyCell="{ column, record }">
                        <!-- 名称列 -->
                        <template v-if="column.dataIndex === 'name'">
                            <span class="name-text">{{ record.name }}</span>
                        </template>

                        <!-- 启用状态 -->
                        <template v-else-if="column.dataIndex === 'enabled'">
                            <span :style="{ color: isEnabled(record) ? '#52c41a' : '#fa541c' }">
                                {{ isEnabled(record) ? '启用' : '停用' }}
                            </span>
                        </template>

                        <!-- 操作列 -->
                        <template v-else-if="column.key === 'actions'">
                            <div class="row-actions">
                                <a-button type="link" class="link-btn" danger
                                    @click.stop="onDelete(record)">删除</a-button>
                                <a-divider type="vertical" />
                                <a-button type="link" class="link-btn" @click.stop="onEdit(record)">编辑</a-button>
                                <a-divider type="vertical" />
                                <a-button type="link" class="link-btn" :disabled="isEnabled(record)"
                                    @click.stop="onEnable(record)">
                                    启用
                                </a-button>
                                <a-divider type="vertical" />
                                <a-button type="link" class="link-btn" :disabled="!isEnabled(record)"
                                    @click.stop="onDisable(record)">
                                    停用
                                </a-button>
                                <!-- <a-divider type="vertical" /> -->
                                <!-- <a-button type="link" class="link-btn" @click.stop="action('测试', record)">测试</a-button> -->
                                <!-- <a-divider type="vertical" /> -->
                                <!-- <a-button type="link" class="link-btn" @click.stop="action('拷贝', record)">拷贝</a-button> -->
                            </div>
                        </template>
                    </template>
                </a-table>
            </div>
        </div>

        <!-- 底部：全选 + 统计 + 分页 -->
        <div class="table-footer">
            <div class="footer-left">
                <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="handleCheckAll">
                    全选
                </a-checkbox>
            </div>

            <div class="footer-right">
                <span class="stat">本页 {{ pageData.length }} 条，共 {{ total }} 条</span>
                <a-pagination :current="current" :pageSize="pageSize" :total="total" show-less-items show-quick-jumper
                    show-size-changer :pageSizeOptions="['10', '20', '50', '100']" @change="handlePageChange"
                    @showSizeChange="handlePageSizeChange" />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import type { TableColumnsType } from 'ant-design-vue'
import { message, Modal } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import api from '@/api'

const router = useRouter()

type RowItem = {
    id: number | string
    name: string
    type?: string
    public?: string
    enabled?: number | string | boolean
    publishTime?: string
    __raw?: any
}

/* ---------- 时间格式化 ---------- */
function pad(n: number) { return n < 10 ? `0${n}` : `${n}` }
function formatToSecond(input: any): string {
    if (input == null || input === '') return ''
    let d: Date
    if (typeof input === 'number') d = input < 1e12 ? new Date(input * 1000) : new Date(input)
    else if (typeof input === 'string') {
        const s = input.replace('T', ' ').replace('Z', '')
        const tryDate = new Date(s)
        if (isNaN(tryDate.getTime())) return input
        d = tryDate
    } else if (input instanceof Date) d = input
    else return ''
    const y = d.getFullYear(), m = pad(d.getMonth() + 1), day = pad(d.getDate())
    const hh = pad(d.getHours()), mm = pad(d.getMinutes()), ss = pad(d.getSeconds())
    return `${y}-${m}-${day} ${hh}:${mm}:${ss}`
}

/* -------- 状态 -------- */
const loading = ref(false)
const keyword = ref('')

const current = ref(1)
const pageSize = ref(10)
const total = ref(0)
const list = ref<RowItem[]>([])

/** 分页 */
const pageData = computed(() => list.value)

/* 选择 */
const selectedRowKeys = ref<(string | number)[]>([])
const rowSelectionCfg = computed(() => ({
    selectedRowKeys: selectedRowKeys.value,
    onChange: (keys: (string | number)[]) => (selectedRowKeys.value = keys),
}))

const checkAll = computed(() => {
    const ids = pageData.value.map(d => d.id)
    return ids.length > 0 && ids.every(id => selectedRowKeys.value.includes(id))
})
const indeterminate = computed(() => {
    const ids = pageData.value.map(d => d.id)
    const checkedCount = selectedRowKeys.value.filter(id => ids.includes(id)).length
    return checkedCount > 0 && checkedCount < ids.length
})
function handleCheckAll(e: any) {
    const ids = pageData.value.map(d => d.id)
    selectedRowKeys.value = e.target.checked
        ? Array.from(new Set([...selectedRowKeys.value, ...ids]))
        : selectedRowKeys.value.filter(id => !ids.includes(id))
}

/* -------- 列 -------- */
const columns = ref<TableColumnsType<RowItem>>([
    // { title: '接口ID', dataIndex: 'id', width: 140 },
    { title: '接口名称', dataIndex: 'name', width: 160 },
    { title: '接口类型', dataIndex: 'type' },
    { title: '公开状态', dataIndex: 'public', width: 100 },
    { title: '启用状态', dataIndex: 'enabled', width: 100 },
    { title: '发布时间', dataIndex: 'publishTime', width: 180 },
    { title: '操作', key: 'actions', fixed: 'right', width: 320 },
])

/* -------- 启停 -------- */
function isEnabled(record: RowItem): boolean {
    const raw = record.__raw?.interface_enable
    const v = raw !== undefined ? raw : record.enabled
    const n = typeof v === 'boolean' ? (v ? 1 : 0) : Number(String(v).trim())
    return n === 1
}

/* -------- 列表请求 -------- */
async function fetchList() {
    loading.value = true
    try {
        const res: any = await api.searchInterfacePageList({
            interface_name: keyword.value || undefined,
            page: current.value,
            page_size: pageSize.value,
        })
        if (res?.code !== 1000) throw new Error(res?.msg || '请求失败')

        const payload = res.data || {}
        const rows: any[] = payload.data || []
        total.value = Number(payload.total || 0)

        list.value = rows.map((it, idx) => {
            const rawTime =
                it.publish_time ??
                it.update_time ??
                it.create_time ??
                it.updated_at ??
                it.created_at ??
                ''
            return {
                id: it.id ?? it.interface_id ?? `${(current.value - 1) * pageSize.value + idx}`,
                name: it.interface_name ?? it.name ?? '',
                type: it.interface_type ?? it.type ?? '',
                public: it.interface_open ?? it.public ?? '',
                enabled: Number(
                    it.interface_enable !== undefined ? it.interface_enable : (it.enabled ?? 0)
                ),
                publishTime: formatToSecond(rawTime),
                __raw: it,
            } as RowItem
        })
    } catch (e: any) {
        message.error(e?.message || '获取列表失败')
    } finally {
        loading.value = false
    }
}

/* —— 路由跳转 —— */
function onAdd() {
    router.push({ path: '/competenceCenterPage', query: { mode: 'create' } })
}
function onEdit(record: RowItem) {
    router.push({ path: '/competenceCenterPage', query: { mode: 'edit', id: String(record.id) } })
}
function onViewDetail(record: RowItem) {
    router.push({ path: '/competenceCenterInfo', query: { id: String(record.id) } })
}

/* ================== 启用 / 停用 ================== */
async function updateStatus(ids: (string | number)[], enable: boolean) {
    const res: any = await api.updateInterfaceStatus({
        interface_ids: ids,
        enable,
    })
    if (res?.code !== 1000) throw new Error(res?.msg || '操作失败')
    return res
}

/** 单条启用 */
async function onEnable(record: RowItem) {
    if (isEnabled(record)) return
    try {
        loading.value = true
        await updateStatus([record.id], true)
        message.success('已启用')
        await fetchList()
    } catch (e: any) {
        message.error(e?.message || '启用失败')
    } finally {
        loading.value = false
    }
}

/** 单条停用 */
async function onDisable(record: RowItem) {
    if (!isEnabled(record)) return
    try {
        loading.value = true
        await updateStatus([record.id], false)
        message.success('已停用')
        await fetchList()
    } catch (e: any) {
        message.error(e?.message || '停用失败')
    } finally {
        loading.value = false
    }
}

/** 批量启用 */
async function onBatchEnable() {
    if (!selectedRowKeys.value.length) return
    try {
        loading.value = true
        await updateStatus(selectedRowKeys.value as (string | number)[], true)
        selectedRowKeys.value = []
        message.success('批量启用成功')
        await fetchList()
    } catch (e: any) {
        message.error(e?.message || '批量启用失败')
    } finally {
        loading.value = false
    }
}

/** 批量停用 */
async function onBatchDisable() {
    if (!selectedRowKeys.value.length) return
    try {
        loading.value = true
        await updateStatus(selectedRowKeys.value as (string | number)[], false)
        selectedRowKeys.value = []
        message.success('批量停用成功')
        await fetchList()
    } catch (e: any) {
        message.error(e?.message || '批量停用失败')
    } finally {
        loading.value = false
    }
}

/** 当前页全部启用 */
async function onAllEnable() {
    const ids = idsOfCurrentPage()
    if (!ids.length) return
    try {
        loading.value = true
        await updateStatus(ids, true)
        selectedRowKeys.value = []
        message.success('当前页已全部启用')
        await fetchList()
    } catch (e: any) {
        message.error(e?.message || '全部启用失败')
    } finally {
        loading.value = false
    }
}

/** 当前页全部停用 */
async function onAllDisable() {
    const ids = idsOfCurrentPage()
    if (!ids.length) return
    try {
        loading.value = true
        await updateStatus(ids, false)
        selectedRowKeys.value = []
        message.success('当前页已全部停用')
        await fetchList()
    } catch (e: any) {
        message.error(e?.message || '全部停用失败')
    } finally {
        loading.value = false
    }
}

/* ================== 删除 ================== */
function onDelete(record: RowItem) {
    Modal.confirm({
        title: `确认删除「${record.name}」？`,
        onOk: async () => {
            try {
                loading.value = true
                const willDeleteLastOneOnPage = pageData.value.length === 1 && current.value > 1
                if (willDeleteLastOneOnPage) current.value -= 1

                const res: any = await api.deleteSearchInterface({ interface_ids: [record.id] })
                if (res?.code !== 1000) throw new Error(res?.msg || '删除失败')

                selectedRowKeys.value = selectedRowKeys.value.filter(k => k !== record.id)
                message.success('删除成功')
                await fetchList()
            } catch (e: any) {
                message.error(e?.message || '删除失败')
            } finally {
                loading.value = false
            }
        },
    })
}

function onBatchDelete() {
    if (!selectedRowKeys.value.length) return
    Modal.confirm({
        title: '确认删除所选项？',
        onOk: async () => {
            try {
                loading.value = true
                const deletingCount = selectedRowKeys.value.length
                const isDeletingWholePage = deletingCount === pageData.value.length && current.value > 1
                if (isDeletingWholePage) current.value -= 1

                const res: any = await api.deleteSearchInterface({
                    interface_ids: selectedRowKeys.value as (string | number)[],
                })
                if (res?.code !== 1000) throw new Error(res?.msg || '批量删除失败')

                selectedRowKeys.value = []
                message.success('批量删除成功')
                await fetchList()
            } catch (e: any) {
                message.error(e?.message || '批量删除失败')
            } finally {
                loading.value = false
            }
        },
    })
}


function idsOfCurrentPage(): (number | string)[] {
    return pageData.value.map(r => r.id)
}

/* —— 详情 —— */
function handleRowClick(record: RowItem, e: MouseEvent) {
    const target = e.target as HTMLElement
    if (
        target.closest('.ant-table-selection-column') ||
        target.closest('.row-actions') ||
        target.closest('.ant-checkbox-wrapper') ||
        target.closest('.ant-btn') ||
        target.closest('a')
    ) return
    onViewDetail(record)
}
function customRow(record: RowItem) {
    return { onClick: (e: MouseEvent) => handleRowClick(record, e) }
}


function action(type: string, record: RowItem) {
    message.info(`${type}: ${record.name}`)
}

/* 搜索/分页 */
function onSearch() { current.value = 1; fetchList() }
function handlePageChange(p: number) { current.value = p; fetchList() }
function handlePageSizeChange(_: number, size: number) { pageSize.value = size; current.value = 1; fetchList() }

onMounted(fetchList)
</script>

<style lang="less" scoped>
.ability-page {
    min-height: 100vh;
    height: auto;
    display: flex;
    flex-direction: column;
    background: #fff;
}

.toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 24px;
    border-bottom: 1px solid #f0f0f0;
    background: #fff;
}

.table-scroll {
    flex: 0 0 auto;
    min-height: 0;
    overflow: visible;
    background: #fff;
}

.table-wrap {
    padding: 24px;
}

.table-wrap :deep(.ant-table-tbody > tr.clickable-row) {
    cursor: pointer;
}

.table-footer {
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 8px 12px;
    border-top: 1px solid #f0f0f0;
    background: #fff;
}

.footer-right {
    display: flex;
    align-items: center;
    gap: 12px;
}

.stat {
    color: #666;
}

.table-wrap :deep(.ant-table-thead > tr > th),
.table-wrap :deep(.ant-table-tbody > tr > td) {
    padding-top: 0 !important;
    padding-bottom: 0 !important;
    height: 40px;
    line-height: 40px;
}

.table-wrap :deep(.ant-table-thead > tr > th) {
    font-weight: 400;
    background-color: #F4F8FD !important;
}

.table-wrap :deep(.ant-table-cell) {
    white-space: nowrap;
}

/* 操作区 */
.table-wrap :deep(.row-actions) {
    display: flex;
    align-items: center;
}

.table-wrap :deep(.link-btn) {
    padding: 0 2px;
    height: auto;
}

.table-wrap :deep(.ant-divider-vertical) {
    margin: 0 6px;
}

.table-wrap :deep(.ant-table-wrapper) {
    background: #fff;
}

.table-wrap :deep(.name-text) {
    color: #333;
}

:deep(.ant-pagination) {
    margin: 0;
}

@media (max-width: 768px) {
    .table-footer {
        flex-wrap: wrap;
        gap: 8px;
    }

    .footer-right {
        margin-left: auto;
    }
}
</style>
